package com.wangjie.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.wangjie.domain.PageResult;
import com.wangjie.domain.dto.UserDto;
import com.wangjie.domain.dto.UserQueryDto;
import com.wangjie.domain.entity.User;
import com.wangjie.domain.vo.UserVo;
import com.wangjie.service.UserService;
import com.wangjie.mapper.UserMapper;
import com.wangjie.utils.BeanCopyUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.util.CollectionUtils;
import org.springframework.util.StringUtils;

import java.util.List;

@Service
public class UserServiceImpl extends ServiceImpl<UserMapper, User> implements UserService {
    @Autowired
    private UserMapper userMapper;

    @Override
    public PageResult<UserVo> pageUserList(Integer pageNum, Integer pageSize, UserQueryDto dto) {
        LambdaQueryWrapper<User> wrapper = new LambdaQueryWrapper<>();
        wrapper.like(StringUtils.hasText(dto.getUserName()), User::getUserName, dto.getUserName())
                .like(StringUtils.hasText(dto.getPhoneNumber()), User::getPhoneNumber, dto.getPhoneNumber())
                .eq(StringUtils.hasText(dto.getStatus()), User::getStatus, dto.getStatus())
                .orderByDesc(User::getCreateTime);

        Page<User> page = new Page<>(pageNum, pageSize);
        this.page(page, wrapper);
        List<User> records = page.getRecords();
        // 转换成 UserVo
        List<UserVo> list = BeanCopyUtils.copyBeanList(records, UserVo.class);

        PageResult<UserVo> result = new PageResult<>();
        result.setRows(list);
        result.setTotal(page.getTotal());
        return result;
    }

    @Override
    public UserVo getUserById(Long id) {
        User user = userMapper.selectById(id);
        UserVo userVo = BeanCopyUtils.copyBean(user, UserVo.class);
        return userVo;
    }

    @Override
    public boolean addUser(UserDto dto) {
        User user = BeanCopyUtils.copyBean(dto, User.class);
        return this.save(user);
    }

    @Override
    public boolean updateUser(UserDto dto) {
        User user = BeanCopyUtils.copyBean(dto, User.class);
        return this.updateById(user);
    }

    @Override
    public boolean deleteUserByIds(List<Long> ids) {
        if (CollectionUtils.isEmpty(ids)) {
            return true;
        }
        return this.removeByIds(ids);
    }
}
